package com.example.team.dao.Imp;

import com.example.team.dao.ITestDao;
import com.example.team.entity.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
/**
 *根据接口操作数据库表的接口规范，对其进行实现
 * 编写者：
 * 时间：
 */
@Repository
public class ITestDaoImpl implements ITestDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int insertUser(Test test) {
        return jdbcTemplate.update(
                "insert into user(id,name,password) " +
                        "values(?,?,?)"
                , test.getId()
                , test.getName()
                , test.getPassword()
        );
    }

    @Override
    public int deleteUser(Test test) {
        return jdbcTemplate.update(
                "delete from user " +
                "where id=?", test.getId());
    }

    @Override
    public int updateUser(Test test) {
        return jdbcTemplate.update("update user set " +
                "name=?,password=? where id=?"
                , test.getName()
                , test.getPassword()
                , test.getId()
        );
    }

    @Override
    public List<Test> getAllUser(Test test) {
        if(test.getName()!=null)
            return jdbcTemplate.query("select " +
                "id,name,password " +
                "from user where name='"+ test.getName()+"'",new Object[]{},
                new BeanPropertyRowMapper<>(Test.class));
        else
            return jdbcTemplate.query("select " +
                "id,name,password " +
                "from user",new Object[]{},
                new BeanPropertyRowMapper<>(Test.class));
    }

    @Override
    public Test getUser(Test test) {
        List<Test> result=jdbcTemplate.query("select " +
                                "id,name,password " +
                                "from user where name='"+ test.getName()+"'",
                        new Object[]{},
                        new BeanPropertyRowMapper<>(Test.class));
        if (result.size()>=1)
            return result.get(0);
        else return null;
    }
}
